﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using CachedServices;
using Core;
using Core.DBInterfaces;
using Core.Email;
using Core.Logging;
using EmailService;
using LoggerService;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using MSSqlDataBase;
using MSSqlDataBase.Repository;
using Core.Users;
using Core.WebScaner;
using WebScanner;

namespace Infrastructure
{
    /// <summary>
    /// Class for regestering classes in ServiceLocator
    /// </summary>
    public sealed class ServiceRegistrator : IContainerAccessor
    {
        private  IUnityContainer _container;
        /// <summary>
        /// The Unity container for the current application
        /// </summary>
        private  IUnityContainer Container
        {
            get
            {
                return _container;
            }
            set
            {
                _container = value;
            }
        }

       IUnityContainer IContainerAccessor.Container
        {
            get
            {
                return Container;
            }
        }

        /// <summary>
        /// Dispose container, use it in destructor
        /// </summary>
        public void CleanUp()
        {
            if (Container != null)
            {
                Container.Dispose();
            }
            UnityServiceLocator sl = ServiceLocator.Current as UnityServiceLocator;
            if (sl != null)
                sl.Dispose();
        } 

        private void InitUnityContainer()
        {
            Container = new UnityContainer().RegisterType<IDbRepository, DbRepository<CMSContext>>().RegisterType<IEmailer, Emailer>().RegisterType<ICacheProvider, DefaultCacheProvider>().RegisterType<IWebCrawler, WebCrawler>();
            
            // регистрируем один единственный экземпляр для всего приложения            
            ILogger logger = new Logger(Container);
            Container.RegisterInstance<ILogger>(logger, new ContainerControlledLifetimeManager());
        }

        /// <summary>
        /// Registering services, use it in app start
        /// </summary>
        public void RegisterServices()
        {
            InitUnityContainer();
            var serviceLocator = new UnityServiceLocator(Container);
            ServiceLocator.SetLocatorProvider(() => serviceLocator);
            DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
        }

        public void RegisterService<T, T2>() where T: class where T2:T
        {
            if (Container == null)
                Container = new UnityContainer();
            
            Container.RegisterType<T, T2>();
        }
    }
}
